<template>
  <div>
    <div style="margin: 10px">
      <el-row :gutter="20">
        <el-col :xl="12" style="margin-top:20px">
          <el-card>
            <template #header>
              <div class="card-header">
                股票持仓
              </div>
            </template>
            <div style="margin-bottom: 10px;">
              <el-tag type="success">LS账号</el-tag>
            </div>
            <el-descriptions
                class="margin-top"
                :column="4"
                border
            >
              <el-descriptions-item align="center">
                <template #label>
                  <div class="cell-item">
                    持仓市值
                  </div>
                </template>
                {{ formatCurrency(lsPositionTotalValue) }}
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="cell-item">
                    持仓盈亏
                  </div>
                </template>
                <span :class="getColorStyle(lsPositionTotalProfit)">
                  {{ formatCurrency(lsPositionTotalProfit) }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="cell-item">
                    净转入资金
                  </div>
                </template>
                {{ formatCurrency(transferData.get('LS')) }}
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="cell-item">
                    清仓盈亏
                  </div>
                </template>
                <span :class="getColorStyle(statStockData.get('LS'))">
                  {{ formatCurrency(statStockData.get('LS')) }}
                </span>
              </el-descriptions-item>
            </el-descriptions>
            <el-table :data="lsPositionList" style="margin-top: 5px;">
              <el-table-column label="证券代码" align="center" prop="stockCode"/>
              <el-table-column label="证券名称" align="center" prop="stockName"/>
              <el-table-column label="当日涨幅"
                               align="center"
                               prop="changePercent"
                               :sort-method="sortChangePercent"
                               sortable>
                <template #default="scope">
                  <span :class="getColorStyle(scope.row.changePercent)">
                     {{ scope.row.changePercent }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="市价" align="center">
                <template #default="scope">
                  <span :class="getColorStyle(scope.row.changePercent)">
                    {{ formatCurrency(scope.row.lastPrice) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="成本价" align="center">
                <template #default="scope">
                  <span v-if="scope.row.stockCode && scope.row.stockCode.endsWith('.HK')">
                    {{ formatCurrency(Math.abs(scope.row.amount) / scope.row.quantity / 0.916) }}
                  </span>
                  <span v-else>
                    {{ formatCurrency(Math.abs(scope.row.amount) / scope.row.quantity) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="持仓数量" align="center" prop="quantity"/>
              <el-table-column label="买入成本" align="center" prop="amount">
                <template #default="scope">
                  {{ formatCurrency(Math.abs(scope.row.amount)) }}
                </template>
              </el-table-column>
              <el-table-column label="市值" align="center" prop="totalValue"/>
              <el-table-column label="持仓盈亏%" align="center">
                <template #default="scope">
                  <span :class="getColorStyle(scope.row.profitPercent)">
                    {{ scope.row.profitPercent }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="持仓盈亏" align="center" prop="profit">
                <template #default="scope">
                  <span :class="getColorStyle(scope.row.profit)">
                    {{ scope.row.profit }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin: 10px 0;">
              <el-tag type="success">XSQ账号</el-tag>
            </div>
            <el-descriptions
                class="margin-top"
                :column="4"
                border
            >
              <el-descriptions-item align="center">
                <template #label>
                  <div class="cell-item">
                    持仓市值
                  </div>
                </template>
                {{ formatCurrency(xsqPositionTotalValue) }}
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="cell-item">
                    持仓盈亏
                  </div>
                </template>
                <span :class="getColorStyle(xsqPositionTotalProfit)">
                  {{ formatCurrency(xsqPositionTotalProfit) }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="cell-item">
                    净转入资金
                  </div>
                </template>
                {{ formatCurrency(transferData.get('XSQ')) }}
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="cell-item">
                    清仓盈亏
                  </div>
                </template>
                <span :class="getColorStyle(statStockData.get('XSQ'))">
                  {{ formatCurrency(statStockData.get('XSQ')) }}
                </span>
              </el-descriptions-item>
            </el-descriptions>
            <el-table :data="xsqPositionList" style="margin-top: 5px;">
              <el-table-column label="证券代码" align="center" prop="stockCode"/>
              <el-table-column label="证券名称" align="center" prop="stockName"/>
              <el-table-column label="当日涨幅"
                               align="center"
                               prop="changePercent"
                               :sort-method="sortChangePercent"
                               sortable>
                <template #default="scope">
                  <span :class="getColorStyle(scope.row.changePercent)">
                     {{ scope.row.changePercent }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="市价" align="center">
                <template #default="scope">
                  <span :class="getColorStyle(scope.row.changePercent)">
                    {{ formatCurrency(scope.row.lastPrice) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="成本价" align="center">
                <template #default="scope">
                  <span v-if="scope.row.stockCode && scope.row.stockCode.endsWith('.HK')">
                    {{ formatCurrency(Math.abs(scope.row.amount) / scope.row.quantity / 0.916) }}
                  </span>
                  <span v-else>
                    {{ formatCurrency(Math.abs(scope.row.amount) / scope.row.quantity) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="持仓数量" align="center" prop="quantity"/>
              <el-table-column label="买入成本" align="center" prop="amount">
                <template #default="scope">
                  {{ formatCurrency(Math.abs(scope.row.amount)) }}
                </template>
              </el-table-column>
              <el-table-column label="市值" align="center" prop="totalValue"/>
              <el-table-column label="持仓盈亏%" align="center">
                <template #default="scope">
                  <span :class="getColorStyle(scope.row.profitPercent)">
                    {{ scope.row.profitPercent }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="持仓盈亏" align="center" prop="profit">
                <template #default="scope">
                  <span :class="getColorStyle(scope.row.profit)">
                    {{ scope.row.profit }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :xl="12" style="margin-top:20px">
          <el-card>
            <template #header>
              <div class="card-header">
                交易任务
              </div>
            </template>
            <div style="margin-bottom: 10px;">
              <el-button
                  size="default"
                  :type="isTradingActive ? 'danger' : 'primary'"
                  @click="toggleTrading"
              >
                {{ isTradingActive ? '停止交易' : '启动交易' }}
              </el-button>
            </div>
            <el-table :data="tradeList">
              <el-table-column label="证券代码" align="center" prop="stockCode"/>
              <el-table-column label="证券名称" align="center" prop="stockName"/>
              <el-table-column label="交易方向" align="center" prop="direction">
                <template #default="scope">
                  <dict-tag :options="trade_direction" :value="scope.row.direction"/>
                </template>
              </el-table-column>
              <el-table-column label="市价" align="center">
                <template #default="scope">
                  <span :class="getColorStyle(scope.row.changePercent)">
                    {{ formatCurrency(scope.row.lastPrice) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="交易价" align="center" prop="price">
                <template #default="scope">
                  {{ formatCurrency(scope.row.price) }}
                </template>
              </el-table-column>
              <el-table-column label="交易股数" align="center" prop="quantity"/>
              <el-table-column label="交易账户" align="center" prop="accountNo">
                <template #default="scope">
                  {{ getAccountName(scope.row.accountNo) }}
                </template>
              </el-table-column>
              <!--              <el-table-column label="交易阶段" align="center" prop="phase">-->
              <!--                <template #default="scope">-->
              <!--                  <dict-tag :options="order_status" :value="scope.row.phase"/>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <el-table-column label="交易状态" align="center" prop="status">
                <template #default="scope">
                  <dict-tag :options="trade_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>


<script setup>
import {amountTransfer} from "@/api/stock/transfer";
import {amountStatStock} from "@/api/stock/stat_stock.js";
import {formatCurrency} from "@/utils/format.js";
import {listStatPosition} from "@/api/stock/stat_position.js";
import {getStockTick} from "@/api/stock/info.js";
import {getTradeMonitorStatus, listTrade, startTradeMonitor, stopTradeMonitor} from "@/api/stock/trade";
import {listAccount} from "@/api/stock/account"; // 引入账户API

const {proxy} = getCurrentInstance();
const {
  trade_direction,
  trade_status,
  order_status
} = proxy.useDict('trade_direction', 'trade_status', 'task_source', 'order_status');

const tradeList = ref([]);
const transferData = ref(new Map());
const statStockData = ref(new Map());
const lsPositionList = ref([]);
const xsqPositionList = ref([]);
const lsPositionTotalValue = ref(0);// LS账户总市值
const lsPositionTotalProfit = ref(0);// LS账户总盈亏
const xsqPositionTotalValue = ref(0);// XSQ账户总市值
const xsqPositionTotalProfit = ref(0);// XSQ账户总盈亏
const dataRefreshTimer = ref(null);
const isTradingActive = ref(false);// 轮询状态
const accountOptions = ref([]);

// 获取实时价格数据
const getRealTimePrices = async () => {
  const allStocks = [...lsPositionList.value, ...xsqPositionList.value];
  if (allStocks.length > 0) {
    const stockCodes = [...new Set(allStocks.map(item => item.stockCode))];
    try {
      const response = await getStockTick({stock_codes: stockCodes.join(',')});
      if (response.data) {
        const priceMap = new Map(Object.entries(response.data));
        updatePositionListWithPrices(lsPositionList.value, priceMap);
        updatePositionListWithPrices(xsqPositionList.value, priceMap);
        updateTradeTaskPrices(tradeList.value, priceMap)
      }
    } catch (error) {
      console.error("获取实时价格失败:", error);
    }
  }
};
// 更新持仓列表市价，市值等信息
const updatePositionListWithPrices = (positionList, priceMap) => {
  let positionTotalValue = 0;
  let positionTotalProfit = 0;
  positionList.forEach(item => {
    const stockData = priceMap.get(item.stockCode);
    if (stockData) {
      // 添加实时价格字段
      item.lastPrice = stockData.lastPrice;
      item.lastClosePrice = stockData.lastClose;
      item.changePercent = '0.00%';
      if (stockData.lastClose !== 0) {
        item.changePercent = ((stockData.lastPrice - stockData.lastClose) / stockData.lastClose * 100).toFixed(2) + '%';
      }

      let totalValue = item.lastPrice * item.quantity; //换算成人民币
      if (item.stockCode.endsWith('.HK')) {
        totalValue = totalValue * 0.916;
      }
      item.totalValue = formatCurrency(totalValue);

      const profit = totalValue + item.amount;
      item.profit = formatCurrency(profit);

      positionTotalValue += totalValue;
      positionTotalProfit += profit;

      item.profitPercent = '0.00%';
      if (totalValue !== 0) {
        const profitPercent = -profit / item.amount * 100;
        item.profitPercent = profitPercent.toFixed(2) + '%';
      }
    }
  });
  if (positionList === lsPositionList.value) {
    lsPositionTotalValue.value = positionTotalValue;
    lsPositionTotalProfit.value = positionTotalProfit;
  } else if (positionList === xsqPositionList.value) {
    xsqPositionTotalValue.value = positionTotalValue;
    xsqPositionTotalProfit.value = positionTotalProfit;
  }
};

// 更新交易任务中的市价信息
const updateTradeTaskPrices = (tradeTaskList, priceMap) => {
  tradeTaskList.forEach(item => {
    const stockData = priceMap.get(item.stockCode);
    if (stockData) {
      item.lastPrice = stockData.lastPrice;
    }
  });
};

// 自定义排序函数，用于按百分比数值大小排序
const sortChangePercent = (a, b) => {
  const aPercent = parseFloat(a.changePercent?.replace('%', '')) || 0;
  const bPercent = parseFloat(b.changePercent?.replace('%', '')) || 0;
  return aPercent - bPercent;
}

// 根据涨跌幅获取颜色样式的方法
const getColorStyle = (number) => {
  if (!number) return '';
  let floatValue;
  if (typeof number === 'string' && number.includes('%')) {
    floatValue = parseFloat(number.replace('%', '')) || 0;
  } else {
    floatValue = parseFloat(number) || 0;
  }
  if (floatValue > 0) {
    return 'text-red';
  } else if (floatValue < 0) {
    return 'text-green';
  }
  return '';
}

//切换交易状态 
const toggleTrading = () => {
  // 先更新状态，再执行操作
  isTradingActive.value = !isTradingActive.value;
  if (isTradingActive.value) {
    startTradeMonitor();
  } else {
    stopTradeMonitor();
  }
};

/** 开始定时获取数据 */
const startDataRefreshTimer = () => {
  // 清除已有的定时器
  if (dataRefreshTimer.value) {
    clearInterval(dataRefreshTimer.value);
  }
  dataRefreshTimer.value = setInterval(() => {
    getRealTimePrices();
  }, 30000);
};

/** 停止定时获取数据 */
const stopDataRefreshTimer = () => {
  if (dataRefreshTimer.value) {
    clearInterval(dataRefreshTimer.value);
    dataRefreshTimer.value = null;
  }
};

/** 获取持仓列表 */
function getPositionList() {
  return listStatPosition({isPage: 'False'}).then(response => {
    lsPositionList.value = response.rows.filter(item => item.accountTag === 'LS');
    xsqPositionList.value = response.rows.filter(item => item.accountTag === 'XSQ');
  });
}

/** 获取转账数据 */
function getTransferData() {
  amountTransfer({}).then(response => {
    transferData.value = new Map(Object.entries(response.data));
  });
}

/** 获取股票统计数据 */
function getStatStockData() {
  amountStatStock({}).then(response => {
    statStockData.value = new Map(Object.entries(response.data));
  });
}

/** 查询股票交易任务列表 */
function getTradeList() {
  return listTrade({isPage: 'False', status: '2'}).then(response => {
    tradeList.value = response.rows;
  });
}

/** 根据账户号码获取账户名称 */
function getAccountName(accountNo) {
  if (!accountNo) return '';
  const account = accountOptions.value.find(item => item.accountNo === accountNo);
  return account ? account.accountName : accountNo;
}

/** 查询账户列表 */
function getAccountList() {
  return listAccount({miniqmt: 'Y'}).then(response => {
    accountOptions.value = response.rows;
  });
}

/** 获取交易状态 */
function getIsTradingActive() {
  getTradeMonitorStatus().then(response => {
    isTradingActive.value = response.data.is_running || false;
  });
}

onMounted(async () => {
  getTransferData();
  getStatStockData();
  getIsTradingActive();
  await getPositionList();
  await getTradeList();
  await getAccountList();
  await getRealTimePrices(); // 获取一次实时价格
  startDataRefreshTimer(); // 启动定时获取实时价格
});

onBeforeUnmount(() => {
  stopDataRefreshTimer();
});
</script>